﻿using System;
using System.Reflection;
using NPOI.SS.UserModel;

namespace Export2Excel
{
    public class ExcelPropertyLocator : IPropertyLocator<int, IRow>
    {
        private PropertyInfo _propertyInfo;
        public PropertyInfo PropertyInfo
        {
            get
            {
                return _propertyInfo;
            }
            set
            {
                _propertyInfo = value;
                _propertyType = _propertyInfo.PropertyType.Name.ToLower();
            }
        }

        public int Key { get; set; }

        private string _propertyType;

        public void SetValue(IRow source, object target)
        {
            ICell cell = source.GetCell(Key);
            object value = GetCellValue(_propertyType, cell);
            PropertyInfo.SetValue(target, value, null);
        }

        private static object GetCellValue(string propertyType, ICell cell)
        {
            object result = null;

            if (cell == null)
            {
                return result;
            }

            if (propertyType.Contains("string"))
            {
                return cell.StringCellValue;
            }

            return result;
        }
    }
}
